<template>
  <el-row class="app-container content" id="app-main">
    <el-col :span="5">
        <catalog
          v-model="query.parentId"
          :tree-data="treeSelectData"
          :default-expanded-keys="defaultExpandedKeys"
          :add-node="handleAdd"
          @on-search="onSearch"
          @delete-node="subDelete"
        />
    </el-col>
    <el-col :span="19">
      <div class="search">
        <div class="head-container">
          <div class="filter-container">
            <el-input
              v-model="query.value"
              clearable
              :placeholder="$t('message.dict.placeholder')"
              style="width: 200px"
              class="filter-item-left"
              size="small"
            />
            <el-button
              class="filter-item-right"
              size="small"
              icon="el-icon-search"
              @click="onSearch"
            >
              {{ $t('message.operate.search') }}
            </el-button>
            <el-button size="small" type="primary" icon="el-icon-refresh-right" @click="onReset">
              {{ $t('message.operate.reset') }}
            </el-button>
          </div>
          <div class="filter-container2">
            <el-button
              v-limit="'XTGL:ZDSJ:ADD'"
              class="filter-item"
              size="small"
              type="primary"
              icon="el-icon-plus"
              @click="handleAdd()"
            >
              {{ $t('message.operate.add') }}
            </el-button>
          </div>
        </div>
        <!-- 表格渲染 -->
        <el-table v-loading="loading" :max-height="maxHeight" :data="data" border>
          <el-table-column prop="dictName" :label="$t('message.dict.dictName')" align="center" />
          <el-table-column prop="dictCode" :label="$t('message.dict.dictCode')" align="center" />
          <el-table-column
            prop="createTime"
            :label="$t('message.dict.createTime')"
            :width="180"
            align="center"
          >
            <template #default="{ row }">
              {{ $dayjs.formateDate(row.createTime, 'YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" :label="$t('message.dict.remark')" align="center" />
          <el-table-column :label="$t('message.operate.name')" width="250" align="center">
            <template #default="scope">
              <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">
                {{ $t('message.operate.edit') }}
              </el-button>
              <el-button icon="el-icon-delete" type="text" @click="subDelete(scope.row.id)">
                {{ $t('message.operate.delete') }}
              </el-button>
              <!-- {{ scope.row.id }} -->
              <el-button icon="el-icon-s-grid" type="text" @click="a(scope.row.id)">
                {{ $t('message.dict.value') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next, jumper"
            :total="total"
            background
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-col>
  </el-row>
  <!-- 新增 -->
  <el-dialog v-if="dialog" v-model="dialog" append-to-body :title="formatTitle" width="800px">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item :label="$t('message.form.type')" prop="type">
        <el-select
          v-model="form.type"
          style="width: 370px"
          :placeholder="$t('message.validate.input')"
        >
          <el-option
            v-for="{ label, value } of options"
            :key="value"
            :label="label"
            :value="value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('message.dict.parent')">
        <popup-tree-input
          :data="treeSelectData"
          :props="{
            children: 'children',
            label: 'dictName',
          }"
          :prop="dictName"
          :default-key="form.parentId"
          node-key="parentId"
          :current-change-handle="clickTree"
        />
      </el-form-item>

      <el-form-item :label="$t('message.dict.catalogName')" prop="dictName">
        <el-input
          v-model="form.dictName"
          style="width: 370px"
          :placeholder="$t('message.validate.input')"
        />
      </el-form-item>
      <el-form-item v-if="form.type === '0'" :label="$t('message.dict.dictCode')" prop="dictCode">
        <el-input
          v-model="form.dictCode"
          style="width: 370px"
          :placeholder="$t('message.validate.input')"
        />
      </el-form-item>
      <el-form-item :label="$t('message.dict.remark')" prop="remark">
        <el-input
          v-model="form.remark"
          style="width: 370px"
          :placeholder="$t('message.validate.input')"
        />
      </el-form-item>
    </el-form>
    <template #footer class="dialog-footer">
      <el-button type="text" @click="dialog = false">{{ $t('message.operate.cancel') }}</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">
        {{ $t('message.operate.confirm') }}
      </el-button>
    </template>
  </el-dialog>
  <dictItem ref="dictItem" />
</template>

<script>
import { saveDict, getDict, updateDict, deleteDict, getDictDatalog } from '../api/dict'
import { findNode } from '../utils/util'
import Catalog from '../components/Catalog'
import PopupTreeInput from '../components/PopupTreeInput'
import dictItem from './components/dictItem.vue'
// import i18n from '@/i18n'
import { get, throttle } from 'lodash'

const options = [
  {
    // label: i18n.global.t('message.dict.catalog'),
    label: '目录',
    value: '1',
  },
  {
    // label: i18n.global.t('message.dict.name'),
    label: '字典',
    value: '0',
  },
]

export default {
  components: { dictItem, Catalog, PopupTreeInput },
  data() {
    return {
      data: [],
      dictDetailData: [],
      loading: false,
      dloading: false,
      qqdialog: false,
      dialog: false,
      ddialog: false,
      isAdd: false,
      isValueAdd: false,
      visible: false,
      treeSelectData: [
        {
          children: [],
          dictName: this.$i18n.t('message.dict.top'),
          id: undefined,
        },
      ],
      options,
      form: {
        id: '',
        dictName: '',
        dictCode: '',
        description: '',
        remark: '',
        type: '1', // 类型
        parentId: '', // 父节点id
      },
      currentPage: 1,
      pageSize: 10,
      total: 0, // 总数量
      // 名称
      dictName: '',
      delLoading: false,
      dictCatalog: [], // 字典目录
      rules: {
        dictName: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'blur' },
        ],
        dictCode: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'blur' },
        ],
        description: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'blur' },
        ],
      },
      queryTypeOptions: [
        { key: 'dictName', display_name: this.$i18n.t('message.dict.dictName') },
        { key: 'description', display_name: this.$i18n.t('message.dict.description') },
      ],
      query: {
        parentId: '',
        value: '', // 快速编码
      },
      defaultExpandedKeys: [],
      height: 0,
    }
  },
  computed: {
    maxHeight() {
      return this.height - 158
    },
    formatTitle() {
      if (this.isAdd && this.form.type == '1') {
        return this.$t('message.dict.add2')
      } else if (this.isAdd && this.form.type == '0') {
        return this.$t('message.dict.add')
      } else {
        return this.$t('message.dict.edit')
      }
    },
  },
  mounted() {
    this.getDictData()
    this.handleDictDatalog()
    this.height = document.getElementById('app-main').offsetHeight
  },
  methods: {
    a: function (val) {
      this.$refs.dictItem.doSubmit(val)
    },
    onReset() {
      this.query = {
        value: '',
        parentId: '',
      }
      this.currentPage = 1
      this.onSearch()
    },
    onSearch() {
      this.getDictData()
    },
    handleDictDatalog() {
      getDictDatalog().then(({ data }) => {
        this.dictCatalog = get(data, 'data')
        this.treeSelectData = this.dictCatalog
        this.defaultExpandedKeys = this.dictCatalog.map((item) => item.id)
      })
    },
    // 获取字典详情
    getDictData: function () {
      this.loading = true
      const params = {
        dictName: this.query.value,
        dictCode: this.query.value,
        current: this.currentPage,
        parentId: this.query.parentId,
        size: this.pageSize,
      }
      getDict(params).then((res) => {
        this.data = res.data.data.records
        this.total = res.data.data.total
        this.loading = false
      })
    },
    // 点击父节点
    clickTree({ id, dictName }) {
      this.form.parentId = id
      this.dictName = dictName
    },
    // 字典名称提交动作
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            // 新增字典
            this.dialog = false
            throttle(
              saveDict(this.form).then((res) => {
                if (res.data.code === 200) {
                  this.$message({ message: res.data.msg, type: 'success' })
                  this.handleDictDatalog()
                } else {
                  this.$message({ message: res.data.msg, type: 'error' })
                }
                this.getDictData()
                this.$refs['form'].resetFields()
              }),
              1000
            )
          } else {
            // 更新字典
            this.dialog = false
            throttle(
              updateDict(this.form).then((res) => {
                if (res.data.code === 200) {
                  this.$message({ message: res.data.msg, type: 'success' })
                } else {
                  this.$message({ message: res.data.msg, type: 'error' })
                }
                this.getDictData()
              }),
              1000
            )
          }
        }
      })
    },
    // 添加字典
    handleAdd: function (initialValues = {}, dictName = '') {
      this.dialog = true
      this.isAdd = true
      this.form = initialValues
      if (dictName != '') {
        this.form.type = '1'
      } else {
        this.form.type = '0'
      }
      this.dictName = dictName
    },
    // 编辑字典
    handleEdit: function (row) {
      this.dialog = true
      this.isAdd = false
      this.form = { ...row }
      this.form.parentId = row.parentId ?? ''
      this.dictName = get(
        findNode(this.treeSelectData, { id: row.parentId }),
        'dictName',
        this.$i18n.t('message.dict.top')
      )
    },
    // 删除操作
    subDelete(val) {
      this.$confirm(this.$i18n.t('message.dict.isDelete'), this.$i18n.t('message.validate.hint'), {
        confirmButtonText: this.$i18n.t('message.operate.confirm'),
        cancelButtonText: this.$i18n.t('message.operate.cancel'),
        type: 'warning',
      }).then(() => {
        deleteDict(val)
          .then((res) => {
            if (res.data.code === 200) {
              this.delLoading = false
              this.$message({ message: res.data.msg, type: 'success' })
              this.getDictData()
              this.handleDictDatalog()
            }
          })
          .catch((err) => {
            this.delLoading = false
          })
      })
    },
    // 换页
    handleCurrentChange: function (val) {
      this.currentPage = val
      this.getDictData()
    },
  },
}
</script>

<style scoped lang="scss">
.filter-item {
  margin-left: 20px;
}
.el-form {
  .el-form-item {
    width: 65%;
    margin: 0 auto;
    margin-bottom: 20px;
  }
}
</style>
